package core.tool.htmlparser.samples;

import org.htmlparser.Node;
import org.htmlparser.NodeFilter;
import org.htmlparser.Parser;
import org.htmlparser.filters.TagNameFilter;
import org.htmlparser.tags.TableTag;
import org.htmlparser.util.NodeList;

public class TestHTMLParser2 {
	/**
	 * 读取目标html内容
	 *
	 */
	public static void testHtml() {
		try {
			String sCurrentLine;
			String sTotalString;
			sCurrentLine = "";
			sTotalString = "";
			java.io.InputStream l_urlStream;
			java.net.URL l_url = new java.net.URL(
					"http://10.249.187.199:8083/injs100/");
			java.net.HttpURLConnection l_connection = (java.net.HttpURLConnection) l_url
					.openConnection();
			l_connection.connect();
			l_urlStream = l_connection.getInputStream();
			java.io.BufferedReader l_reader = new java.io.BufferedReader(
					new java.io.InputStreamReader(l_urlStream));
			while ((sCurrentLine = l_reader.readLine()) != null) {
				sTotalString += sCurrentLine + "\r\n";
			}

			String testText = extractText(sTotalString);
		} catch (Exception e) {
			e.printStackTrace();
		}

	}
    /**
     * 抽取纯文本信息
     * @param inputHtml：html文本
     * @return
     * @throws Exception
     */
	public static String extractText(String inputHtml) throws Exception {
		StringBuffer text = new StringBuffer();
		Parser parser = Parser.createParser(new String(inputHtml.getBytes(),
				"GBK"), "GBK");
		// 遍历所有的节点
		NodeList nodes = parser.extractAllNodesThatMatch(new NodeFilter() {
			public boolean accept(Node node) {
				return true;
			}
		});

		System.out.println(nodes.size());
		for (int i = 0; i < nodes.size(); i++) {
			Node nodet = nodes.elementAt(i);
			//字符串的代表性节点:节点的描述
			text.append(new String(nodet.toPlainTextString().getBytes("GBK"))
					+ "\r\n");
		}
		return text.toString();
	}
    /**
     *  读取文件的方式/utl 来分析内容. filePath也可以是一个Url.
     * @param resource :文件/Url
     * @throws Exception
     */
	public static void test5(String resource) throws Exception {
		Parser myParser = new Parser(resource);
		myParser.setEncoding("GBK");
		String filterStr = "table";
		NodeFilter filter = new TagNameFilter(filterStr);
		NodeList nodeList = myParser.extractAllNodesThatMatch(filter);
		/*for(int i=0;i<nodeList.size();i++)
		{
			TableTag tabletag = (TableTag) nodeList.elementAt(i);
			//标签名称
			System.out.println(tabletag.getTagName());
			System.out.println(tabletag.getText());
		}*/
		TableTag tabletag = (TableTag) nodeList.elementAt(1);
		
		
		

	}

	public static void main(String[] args) throws Exception {
		//test5("http://10.249.187.199:8083/injs100/");
		testHtml();
	}
}

